const router = require('koa-router')();
const DB = require('../../module/db.js');
const tools = require('../../module/tools.js');


router.get('/', async (ctx) => {
	
	let result = await DB.findOne('nav', {});
	
    await ctx.render('admin/nav/list', {
    	list: result
    });
});



router.get('/add', async (ctx) => {

    await ctx.render('admin/nav/add');
});

router.post('/add', async (ctx) => {

	let title = ctx.request.body.title;
	let url = ctx.request.body.url;
	let sort = ctx.request.body.sort ? parseInt(ctx.request.body.sort, 0) : 0;
	let status = ctx.request.body.status ? parseInt(ctx.request.body.status, 0) : 0;
	
	let addResult = await DB.insertOne('nav', {
        title,
        url,
        sort,
        status,
        add_time: new Date(),
    });
    
    ctx.redirect(ctx.state.__HOST__ + '/admin/nav');
});



router.get('/edit', async (ctx) => {

    let id = ctx.query.id;
    let result = await DB.findOne('nav', {
        _id: DB.getObjectID(id)
    });

    await ctx.render('admin/nav/edit', {
        list: result[0],
        referer: ctx.state.G.referer
    });
});

router.post('/edit', async (ctx) => {

    let id = ctx.request.body.id;
    let referer = ctx.request.body.referer || '';
    
    let json = {
    	title: ctx.request.body.title.trim(),
    	url: ctx.request.body.url.trim(),
    	sort: ctx.request.body.sort.trim()
    }
    
    let addResult = await DB.updateOne('nav', {
    	_id: DB.getObjectID(id)
	}, json);

    (referer) ? ctx.redirect(referer) : ctx.redirect(ctx.state.__HOST__ + '/admin/nav');
});


router.get('/delete', async (ctx) => {

    ctx.body = '删除用户';
});

module.exports = router.routes();